package com.zbcz.crm

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Spinner
import androidx.activity.viewModels
import androidx.fragment.app.FragmentActivity
import com.google.android.material.datepicker.MaterialDatePicker
import com.zbcz.crm.CustomerSelectorActivity.Companion.CUSTOMER_DATA
import com.zbcz.crm.adapter.CustomSpinnerAdapter
import com.zbcz.crm.bean.CommonListBean
import com.zbcz.crm.bean.CommonSpinnerBean
import com.zbcz.crm.bean.Contacts
import com.zbcz.crm.bean.Customer
import com.zbcz.crm.databinding.ActivityUserCreateBinding
import com.zbcz.crm.databinding.ItemCommonListBinding
import com.zbcz.crm.util.IS_TEST_MODE
import com.zbcz.crm.util.ToastUtils
import com.zbcz.crm.viewmodel.ContactsAddViewModel
import com.zbcz.crm.viewmodel.CustomSelectorViewModel
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.UUID

class ContactsAddActivity : BaseActivity() {


    private lateinit var mBinding: ActivityUserCreateBinding

    private val mViewModel: ContactsAddViewModel by viewModels()

    companion object {
        private const val ADD_CONTACTS_NAME = 1
        private const val ADD_CONTACTS_CUSTOMER_NAME = 2
        private const val ADD_CONTACTS_PHONE = 3
        private const val ADD_CONTACTS_BIRTHDAY = 4
        private const val ADD_CONTACTS_CELLPHONE = 5
        private const val ADD_CONTACTS_EMAIL = 6
        private const val ADD_CONTACTS_JOB_TITLE = 7
        private const val ADD_CONTACTS_ADDRESS = 8
        private const val ADD_CONTACTS_IS_KEY_DECIDER = 9
        private const val ADD_CONTACTS_GENDER = 10
        private const val ADD_CONTACTS_REMARK = 11
        private const val SELECT_CUSTOMER_REQUEST = 100

        val genders = arrayOf(
            CommonSpinnerBean("请选择", ""),
            CommonSpinnerBean("男", "0"),
            CommonSpinnerBean("女", "1")
        )
        val isDecider = arrayOf(
            CommonSpinnerBean("请选择", ""),
            CommonSpinnerBean("是", "0"),
            CommonSpinnerBean("否", "1")
        )

        fun convertDateFormat(dateString: String): String {
            // 使用正则表达式匹配并替换日期格式
            val regex = Regex("""(\d{4})年(\d{1,2})月(\d{1,2})日""")
            return dateString.replace(regex) { result ->
                val year = result.groupValues[1]
                val month = result.groupValues[2]
                val day = result.groupValues[3]
                "$year-$month-$day"
            }
        }

        fun isValidLandline(phone: String): Boolean {
            // 正则表达式用于匹配典型的座机号码格式，区号是可选的，号码部分是6到8位数字
            val regex = """(\(?\d{3,4}\)?[-.\s]?)?\d{6,8}""".toRegex()
            return regex.matches(phone)
        }

        val addContactsList = listOf(
            CommonListBean("名称", "请输入", ADD_CONTACTS_NAME, "张三", R.id.add_contacts_name),
            CommonListBean(
                "客户名称",
                "请输入",
                ADD_CONTACTS_CUSTOMER_NAME,
                if (IS_TEST_MODE) "ABC 公司" else "",
                R.id.add_contacts_customer_name
            ),
            CommonListBean(
                "座机",
                "请输入",
                ADD_CONTACTS_PHONE,
                if (IS_TEST_MODE) "18734831522" else "",
                R.id.add_contacts_phone
            ),
            CommonListBean(
                "生日",
                "请输入",
                ADD_CONTACTS_BIRTHDAY,
                if (IS_TEST_MODE) "1990年1月1日" else "",
                R.id.add_contacts_birthday
            ),
            CommonListBean(
                "手机",
                "请输入",
                ADD_CONTACTS_CELLPHONE,
                if (IS_TEST_MODE) "18734831522" else "",
                R.id.add_contacts_cellphone
            ),
            CommonListBean(
                "电子邮件",
                "请输入",
                ADD_CONTACTS_EMAIL,
                if (IS_TEST_MODE) "zhangsan@example.com" else "",
                R.id.add_contacts_email
            ),
            CommonListBean(
                "职务",
                "请输入",
                ADD_CONTACTS_JOB_TITLE,
                if (IS_TEST_MODE) "经理" else "",
                R.id.add_contacts_job_title
            ),
            CommonListBean(
                "地址",
                "请输入",
                ADD_CONTACTS_ADDRESS,
                if (IS_TEST_MODE) "中国北京市朝阳区" else "",
                R.id.add_contacts_address
            ),
            CommonListBean(
                "是否关键决策人",
                "请选择是否关键决策人",
                ADD_CONTACTS_IS_KEY_DECIDER,
                if (IS_TEST_MODE) "是" else "",
                R.id.add_contacts_is_key_decider
            ),
            CommonListBean(
                "性别",
                "请选择性别",
                ADD_CONTACTS_GENDER,
                if (IS_TEST_MODE) "男" else "",
                R.id.add_contacts_gender
            ),
            CommonListBean(
                "备注",
                "请输入备注",
                ADD_CONTACTS_REMARK,
                if (IS_TEST_MODE) "这是一个测试备注。" else "",
                R.id.add_contacts_remark
            )
        )

        fun generateUUID(): String {
            return UUID.randomUUID().toString()
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mBinding = ActivityUserCreateBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        super.onCreate(savedInstanceState)
        init()
    }

    fun init() {
        mBinding.tvTitle.text = "新建联系人"
        mBinding.llAddContacts.visibility = View.VISIBLE
        mBinding.rcList.visibility = View.GONE
        mBinding.tvCancel.setOnClickListener {
            finish()
        }
        addViews(addContactsList)
        mBinding.tvConfirm.setOnClickListener {
            submitData()
        }
        mViewModel.mAddContactsResponse.observe(this) { isSuccess ->
            if (isSuccess) {
                finish()
            }
        }
        mBinding.ivBack.setOnClickListener {
            finish()
        }
    }

    private fun addViews(itemList: List<CommonListBean>) {
        // 获取 LayoutInflater 实例
        val inflater = layoutInflater

        // 创建 LayoutParams
        val layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )

        // 循环遍历 itemList 列表
        for (item in itemList) {
            // 根据 item_common_list 布局文件创建 ViewBinding 实例
            val itemBinding = ItemCommonListBinding.inflate(inflater, null, false)
            itemBinding.root.id = item.id!!
            // 设置标题和提示文本
            itemBinding.tvTitle.text = item.title
            itemBinding.edContent.hint = item.hintText
            // 设置 id
            itemBinding.root.id = item.id ?: View.generateViewId()
            itemBinding.ivDivider.visibility =
                if (itemList.indexOf(item) != itemList.size - 1) View.VISIBLE else View.GONE
            itemBinding.edContent.setText(item.value)

            // 添加到 LinearLayout 中
            mBinding.llAddContacts.addView(itemBinding.root, layoutParams)
            when (item.type) {
                ADD_CONTACTS_CUSTOMER_NAME -> {
                    itemBinding.tvChooseCustomer.apply {
                        visibility = View.VISIBLE
                        setOnClickListener {
                            val intent = Intent(
                                this@ContactsAddActivity,
                                CustomerSelectorActivity::class.java
                            )
                            startActivityForResult(intent, SELECT_CUSTOMER_REQUEST)
                        }
                    }
                    itemBinding.edContent.isEnabled = false
                }

                ADD_CONTACTS_BIRTHDAY -> {
                    itemBinding.edContent.isEnabled = false
                    itemBinding.ivDate.visibility = View.VISIBLE
                    itemBinding.ivDate.setOnClickListener {
                        showDatePickerDialog(this)
                    }
                }

                ADD_CONTACTS_GENDER -> {
                    itemBinding.edContent.isEnabled = false
                    itemBinding.edContent.visibility = View.GONE
                    itemBinding.spSelect.visibility = View.VISIBLE
                    initSpinner(itemBinding.spSelect, genders)
                }

                ADD_CONTACTS_IS_KEY_DECIDER -> {
                    itemBinding.edContent.isEnabled = false
                    itemBinding.edContent.visibility = View.GONE
                    itemBinding.spSelect.visibility = View.VISIBLE
                    initSpinner(itemBinding.spSelect, isDecider)
                }

                ADD_CONTACTS_ADDRESS, ADD_CONTACTS_REMARK -> {
                    itemBinding.redStar.visibility = View.GONE
                }
            }
        }
    }

    private var mCustomer: Customer? = null

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == SELECT_CUSTOMER_REQUEST) {
            val resultData = data?.getParcelableExtra(CUSTOMER_DATA) as Customer?
            if (resultData != null) {
                mCustomer = resultData
                findTargetView(R.id.add_contacts_customer_name)?.setText(resultData.customerName)
            }
        }
    }

    private fun findTargetView(parentId: Int): EditText? {
        val parentView: View? = findViewById(parentId)
        return parentView?.findViewById(R.id.ed_content)
    }

    private fun findTargetSpinner(parentId: Int): Spinner? {
        val parentView: View? = findViewById(parentId)
        return parentView?.findViewById(R.id.sp_select)
    }

    private fun showDatePickerDialog(context: Context) {
        // 获取当前日期
        val calendar: Calendar = Calendar.getInstance()
        val year: Int = calendar.get(Calendar.YEAR)
        val month: Int = calendar.get(Calendar.MONTH)
        val dayOfMonth: Int = calendar.get(Calendar.DAY_OF_MONTH)

        // 创建日期选择器
        val builder = MaterialDatePicker.Builder.datePicker()
        builder.setTitleText("")
        builder.setSelection(MaterialDatePicker.todayInUtcMilliseconds())
        val picker = builder.build()

        // 监听日期选择结果
        picker.addOnPositiveButtonClickListener { selection ->
            val date = Date(selection)
            val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            val formattedDate = sdf.format(date)
            findTargetView(R.id.add_contacts_birthday)?.setText(formattedDate)
        }

        // 显示日期选择对话框
        picker.show((context as FragmentActivity).supportFragmentManager, picker.toString())
    }

    private fun initSpinner(spinner: Spinner, options: Array<CommonSpinnerBean>) {
        // 准备数据源
        val adapter = CustomSpinnerAdapter(this, options)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        // 设置适配器
        spinner.adapter = adapter
        // 设置选项选中监听器
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View,
                position: Int,
                id: Long
            ) {
                // 获取选中的选项
                val selectedOption = options[position]
                Log.i(VisitorAddActivity.TAG, "selected$selectedOption")

            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // 当没有选项被选中时的处理逻辑
            }
        }
    }

    private fun submitData() {
        val name = findTargetView(R.id.add_contacts_name)?.text.toString()
        if (name.isBlank()) {
            ToastUtils.show("请输入姓名")
            return
        }

        //val customerName = findTargetView(R.id.add_contacts_customer_name)?.text.toString()

        val cellPhone = findTargetView(R.id.add_contacts_cellphone)?.text.toString()
        if (cellPhone.isBlank()) {
            ToastUtils.show("请输入手机号")
            return
        } else if (!cellPhone.matches(Regex("^1[3-9]\\d{9}\$"))) {
            ToastUtils.show("手机号格式不正确")
            return
        }

        val birthday = findTargetView(R.id.add_contacts_birthday)?.text.toString()

        val phone = findTargetView(R.id.add_contacts_phone)?.text.toString()

        val email = findTargetView(R.id.add_contacts_email)?.text.toString()
        if (email.isBlank()) {
            ToastUtils.show("请输入电子邮件")
            return
        } else if (!email.matches(Regex("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"))) {
            ToastUtils.show("电子邮件格式不正确")
            return
        }

        val jobTitle = findTargetView(R.id.add_contacts_job_title)?.text.toString()

        val address = findTargetView(R.id.add_contacts_address)?.text.toString()

        val isKeyDecider =
            findTargetSpinner(R.id.add_contacts_is_key_decider)?.selectedItem as CommonSpinnerBean?

        val gender = findTargetSpinner(R.id.add_contacts_gender)?.selectedItem as CommonSpinnerBean?

        val remark = findTargetView(R.id.add_contacts_remark)?.text.toString()

        if (TextUtils.isEmpty(isKeyDecider?.value)) {
            ToastUtils.show("请选择是否是关键决策人")
            return
        }

        if (TextUtils.isEmpty(gender?.value)) {
            ToastUtils.show("请选择性别")
            return
        }

        if (mCustomer == null) {
            ToastUtils.show("请选择客户")
            return
        }


        if (phone.isBlank()) {
            ToastUtils.show("请输入电话")
        } else if (!isValidLandline(phone)) {
            ToastUtils.show("座机格式不正确")
        }

        // 创建联系人对象
        val contact = Contacts().apply {
            contactName = name
            this.customerName = mCustomer?.customerName
            contactPhoneNumber = phone
            this.birthday = convertDateFormat(birthday)
            contactPhone = cellPhone
            contactPosition = jobTitle
            contactEmailAddress = email
            companyAddress = address
            isTheKeyDecisionMaker = isKeyDecider?.value.toString()
            contactSex = gender?.value.toString()
            notes = remark
            //id = generateUUID()
            customerId = mCustomer?.id

        }
        mViewModel.addContacts(contact)
    }

}